package offer.offer03;

/**
 * 100, 62中序遍历应该就行了吧。
 * 使用了全局变量, 试试不用?
 */
public class Solution54 {
    private int count = -1;
    private int target = 0;
    public int kthLargest(TreeNode root, int k) {
        count = k;
        findK(root);
        return target;
    }
    //可以不在调用自己的时候判断子树是否为空, 二是像注释的那样, return; 这是void函数提前结束的好办法;
    public void findK(TreeNode node){
        //if(node == null) return;
        if(node.right != null) findK(node.right);
        if(--count == 0){
            target = node.val;
        }else {
            if(node.left != null) findK(node.left);
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(3);
        root.right = new TreeNode(6);
        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(4);
        root.left.left.left = new TreeNode(1);
        System.out.println(new Solution54().kthLargest(root, 3));
    }
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}